//
//  CalendarStream.m
//  Pennyworth Punch Clock
//
//  Created by Chris Karr on 8/23/08.
//  Copyright 2008 Northwestern University. All rights reserved.
//

#import "CalendarStream.h"
#import <CalendarStore/CalendarStore.h>
#import "AppDelegate.h"

#define LOG_CALENDARS @"Log_Calendars"

@implementation CalendarStream

@synthesize timer;

- (void) awakeFromNib
{
	self.timer = [NSTimer scheduledTimerWithTimeInterval:30 target:self selector:@selector(update:) userInfo:nil repeats:YES];
}

- (void) update:(NSTimer *) theTimer
{
	if (![[NSUserDefaults standardUserDefaults] boolForKey:LOG_CALENDARS])
		return;

	NSCalendarDate * now = [NSCalendarDate date];
	
	NSCalendarDate * startDate = [NSCalendarDate dateWithYear:[now yearOfCommonEra] 
														month:[now monthOfYear] 
														  day:[now dayOfMonth]
														 hour:0 
													   minute:0 
													   second:0 
													 timeZone:nil];
	
	NSCalendarDate * endDate = [NSCalendarDate dateWithYear:[now yearOfCommonEra] 
													  month:[now monthOfYear] 
														day:[now dayOfMonth]
													   hour:24 
													 minute:59 
													 second:59
												   timeZone:nil];
	
	for (CalCalendar * calendar in [[CalCalendarStore defaultCalendarStore] calendars])
	{
		NSPredicate * today = [CalCalendarStore eventPredicateWithStartDate:startDate 
																	endDate:endDate
																  calendars:[NSArray arrayWithObject:calendar]];
		
		NSArray * events = [[CalCalendarStore defaultCalendarStore] eventsWithPredicate:today];
		
		NSMutableString * predictions = [NSMutableString string];
		
		for (CalEvent * event in events)
		{
			if ([[event endDate] timeIntervalSinceNow] >= 0 && [[event startDate] timeIntervalSinceNow] <= 0)
			{
				if ([predictions length] > 0)
					[predictions appendString:@"; "];
				
				[predictions appendString:event.title];
			}
		}
		
		NSMutableDictionary * note = [NSMutableDictionary dictionary];
		[note setValue:[NSString stringWithFormat:@"Calendar: %@", calendar.title] forKey:KEY];
		[note setValue:predictions forKey:PREDICTION];
		
		[[NSNotificationCenter defaultCenter] postNotificationName:PREDICTION_FETCHED object:self userInfo:note];
	}
}

@end
